package com.framework.mybatis.plugin;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**
 * 生成实体添加LocalDateTime注解
 *
 * @author LeeJun
 * @create 2017-08-12 17:34
 */
public class DateTimeFormatPlugin extends PluginAdapter {
	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}

	@Override
	public boolean modelFieldGenerated(Field field,
									   TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
									   IntrospectedTable introspectedTable,
									   Plugin.ModelClassType modelClassType) {

		this.generateLocalDateTimeAnnotation(field, topLevelClass);
		return true;
	}

	protected void generateLocalDateTimeAnnotation(Field field, TopLevelClass topLevelClass) {
		String shortName = field.getType().getShortNameWithoutTypeArguments();
		if (shortName.equals("LocalDateTime")) {
			field.addAnnotation("@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")");
		} else if (shortName.equals("LocalDate")) {
			field.addAnnotation("@DateTimeFormat(pattern = \"yyyy-MM-dd\")");
		} else if (shortName.equals("LocalTime")) {
			field.addAnnotation("@DateTimeFormat(pattern = \"HH:mm:ss\")");
		}
		topLevelClass.addImportedType("org.springframework.format.annotation.DateTimeFormat");
	}


}
